#include "httpmgr.h"

HttpMgr::~HttpMgr() {}

HttpMgr::HttpMgr() {
    connect(this,&HttpMgr::sig_http_finish,this,&HttpMgr::slots_http_finish);

}

void HttpMgr::PostHeepReq(QUrl url, QJsonObject json, ReqId req_id,
                          Modules mod) {
  // 解析json 为字符串
  QByteArray data = QJsonDocument(json).toJson();
  QNetworkRequest request(url);

  request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
  request.setHeader(QNetworkRequest::ContentLengthHeader,
                    QByteArray::number(data.length()));

  auto self = shared_from_this();
  QNetworkReply *reply = _manager.post(request, data);

  QObject::connect(
      reply, &QNetworkReply::finished, [self, reply, req_id, mod]() {
        // 处理错误情况
        if (reply->error() != QNetworkReply::NoError) {
          qDebug() << reply->errorString();
          // 发送信号通知完成
          emit self->sig_http_finish(req_id, "", ErrorCodes::ERR_NETWORK, mod);
          // 回收指针
          reply->deleteLater();
          return;
        } else {
          // 无错误
          QString res = reply->readAll();
          // 发送信号通知完成
          emit self->sig_http_finish(req_id, res, ErrorCodes::SUCCESS, mod);
          // 回收指针
          reply->deleteLater();
          return;
        }
      });
}

void HttpMgr::slots_http_finish(ReqId req_id, QString res, ErrorCodes err, Modules mod)
{
    if(mod==Modules::REGISTERMOD){
        // 发送信号通知指定模块http的响应结束了
        emit sig_reg_mod_finish(req_id,res,err);
    }
}
